<template>
  <view class="container" v-if="paper">
    <!-- 由于要滑动，所以采用swiper包裹 -->
    <!-- 滑动试图 -->
    <swiper circular class="swiper-box" @change="handlerChange" :current="current">
      <!-- 为了提高性能和节约流量，做以下处理：
      将看过的图片索引和与它相邻的前后两张图片放到一个数组中，每次循环的时候判断是否在数组中，如果在数组中，就显示
       -->
      <swiper-item v-for="(p,index) in newPaperList" :key="p._id">
        <view class="swiper-item" @click="handlerIsShowMask">
          <image v-if="browsedList.includes(index)" class="img" :src="p.bigPicUrl" mode="aspectFill"></image>
        </view>
      </swiper-item>
    </swiper>
    <!-- 透明遮罩 -->
    <view class="mask-box" v-show="isShow">
      <!-- #ifndef MP-TOUTIAO -->
      <!-- 返回 -->

      <view class="back-box" :style="{top:getStatusHeight()+'px',lineHeight:getCustomNavHeight()+'px'}"
        @click="handlerGoBack">
        <uni-icons :type="isShare?'home-filled':'left'" size="24"></uni-icons>
      </view>
      <!-- #endif -->

      <!-- 指示器 -->
      <view class="indicator-box">
        {{current + 1}} / {{paperList.length}}
      </view>
      <!-- 时间 -->
      <view class="time-box">
        <uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat>
      </view>
      <!-- 日期 -->
      <view class="date-box">
        <uni-dateformat :date="Date.now()" format="MM月dd日"></uni-dateformat>
      </view>
      <!-- 评分下载 -->
      <view class="footer-box" style=" width: 494rpx;">
        <view class="item-box" @click="handlerLookUpDetail">
          <uni-icons type="info" size="27"></uni-icons>
          <view class="text">
            信息
          </view>
        </view>
        <view class="item-box" @click="handlerClickRate">
          <uni-icons type="star" size="27"></uni-icons>
          <view class="text">
            评分
          </view>
        </view>
        <view class="item-box" @click="handlerDownload">
          <uni-icons type="download" size="27"></uni-icons>
          <view class="text">
            下载
          </view>
        </view>
      </view>
    </view>
    <!-- 信息弹窗 -->
    <uni-popup ref="detailpopup">
      <view class="detailpopup-box">
        <my-header :popup="detailpopup"></my-header>
        <!-- 详情内容区 -->
        <scroll-view scroll-y class="scroll-y">
          <view class="row">
            <view class="label">壁纸ID:&nbsp;</view>
            <text selectable class="value">{{paper._id}}</text>
          </view>
          <view class="row">
            <view class="label">发布者:&nbsp;</view>
            <text selectable class="value">哈哈哈</text>
          </view>
          <view class="row">
            <view class="label">评分:&nbsp;</view>
            <uni-rate :value="paper.score" readonly touchable="false" />
            &nbsp;{{paper.score}}分
          </view>
          <view class="row">
            <view class="label">摘要:&nbsp;</view>
            <text class="value ">{{paper.description}}</text>
          </view>
          <view class="row">
            <view class="label">标签:&nbsp;</view>
            <view class="value tag-box">
              <view class="tag" v-for="tag in paper.tabs" :key="tag">{{tag}}</view>
            </view>
          </view>
          <view class="declaration">
            声明：xxxxxxxxxxxxxxxxxxx哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
            xxxxxxxxxxxxxxxx哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 评分弹窗 -->
    <uni-popup ref="ratePopup">
      <view class="rate-container">
        <my-header :popup="ratePopup" :isRated="isRated">
        </my-header>
        <view class="score">
          <uni-rate allowHalf v-model="score" :readonly="isRated" :touchable="isRated"></uni-rate>{{score}}分
        </view>
        <!-- 按钮是否禁用分两种情况 ，所以用逻辑或-->
        <button :disabled="isRated || !score>0 ?true:false" class="confirm-btn" size="mini"
          @click="handlerRate">确认评分</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
  import {
    onLoad,
    onShareAppMessage,
    onShareTimeline,
  } from '@dcloudio/uni-app'
  import {
    nextTick,
    ref
  } from 'vue';
  import http from '@/api/index.js'
  import {
    showMsg
  } from '../../utlis/interact';
  import {
    getStatusHeight,
    getCustomNavHeight
  } from '../../utlis/system-info';
  // 数据
  // 表单数据
  const score = ref(0);
  // 控制结构是否显示的变量
  const isShow = ref(true);
  const isRated = ref(false);
  const isShare = ref(false);
  // 列表渲染所需数组
  const paperList = ref(JSON.parse(uni.getStorageSync('paperlist') || "[]"));
  const newPaperList = ref(generateNewArrByPaperList());
  const current = ref(null);
  const paper = ref(null);
  // 组件实例
  const detailpopup = ref(null);
  const ratePopup = ref(null);
  const browsedList = ref([]);
  // 普通变量
  let _id;
  // 生命周期
  // onLoad被执行时响应式数据已可用
  onLoad(async (options) => {
    const {
      id,
      type
    } = options;
    // 通过id拿到该对象的索引
    current.value = paperList.value.findIndex(pw => pw._id === id);
    paper.value = paperList.value[current.value];
    _id = id;
    // 由于分享的时候需要发请求拿数据，所以传一个type字段，值为share表示通过分享进入，对options进行判断
    if (type === 'share') {
      isShare.value = true;
      current.value = 0;
      const res = await http('api/bizhi/detailWall', {
        id,
      });
      if (res.errCode !== 0) return showMsg();
      paperList.value = res.data;
      newPaperList.value = generateNewArrByPaperList();
    }
    browsedPaperwall();
  });
  // 分享好友功能
  onShareAppMessage(() => {
    return {
      title: '发现一个好看的壁纸，快来看看',
      path: '/subpkg/preview_img/preview_img?id=' + _id + '&type=share'
    }
  });
  // 转发朋友圈功能
  onShareTimeline(() => {
    return {
      title: '发现一个好看的壁纸，快来看看',
      query: "id=" + _id + '&type=share',
      imageUrl: '/static/avatar.jpeg'
    }
  })
  // 事件回调
  //点击swiper中的某一项
  function handlerIsShowMask() {
    isShow.value = !isShow.value
  }
  // swiper滑动
  function handlerChange(e) {
    current.value = e.detail.current;
    // 更新_id
    _id = paperList.value[current.value]._id;
    browsedPaperwall();
  }
  // 点击信息按钮
  function handlerLookUpDetail() {
    detailpopup.value.open('bottom');
    paper.value = newPaperList.value[current.value];
  }
  // 点击下载按钮
  async function handlerDownload() {
    // #ifdef H5
    uni.showModal({
      content: '请长按壁纸进行下载',
      showCancel: false
    })
    // #endif

    // #ifndef H5
    const {
      classid,
      _id: wallId,
      bigPicUrl: src
    } = newPaperList.value[current.value];
    const res = await http('api/bizhi/downloadWall', {
      classid,
      wallId
    });

    if (res.errCode !== 0) return showMsg('下载失败');

    uni.showLoading({
      title: '下载中...',
      mask: true,
    });
    //保存图片到系统相册需要uni.saveImageToPhotosAlbum()和uni.getImageInfo()接口配合使用
    uni.getImageInfo({
      src,
      success(res) {
        uni.saveImageToPhotosAlbum({
          filePath: res.path,
          success(res) {
            showMsg('保存成功，可到相册查看', 3000);
          },
          fail(err) {
            // 在pc端调用失败有两种情况:
            // 1. 保存时用户点击取消
            if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') return showMsg('保存失败，请重新下载');
            // 2. 授权时用户点击拒绝
            uni.showModal({
              title: '提示',
              content: '您已拒绝授权，是否再次授权',
              success(res) {
                if (res.confirm) {
                  uni.openSetting({
                    success(err) {
                      if (err.authSetting['scope.writePhotosAlbum']) return showMsg('授权成功');
                      showMsg('授权失败');
                    },
                    fail(err) {
                      console.log(err);
                    }
                  });
                } else {
                  showMsg('取消授权');
                }
              },
              fail(err) {
                console.log(err)
              }
            });
          },
          complete() {
            uni.hideLoading();
          }
        })
      },
    })
    // #endif

  }
  // 点击评分
  function handlerClickRate() {
    ratePopup.value.open();
    paper.value = paperList.value[current.value];
    if (paper.value.userScore) {
      isRated.value = true;
      score.value = paper.value.userScore;
    } else {
      isRated.value = false;
      score.value = 0;
    }
  }
  // 点击确认评分
  async function handlerRate() {
    const {
      classid,
      _id: wallId
    } = paper.value;
    // 收集表单数据
    const rateForm = {
      classid,
      wallId,
      userScore: score.value + ''
    }

    // 用第一步所收集的数据发请求
    const res = await http('api/bizhi/setupScore', rateForm);
    ratePopup.value.close();
    // 发送请求后给壁纸对象添加一个字段userScore保存评分，并更新本地的壁纸数组
    paperList.value[current.value].userScore = score.value;
    uni.setStorageSync('paperlist', JSON.stringify(paperList.value));
    if (res.errCode !== 0) return showMsg('已评分');
    showMsg('评分成功');
  }
  // 点击了左上角图标
  function handlerGoBack() {
    uni.navigateBack({
      fail() {
        uni.reLaunch({
          url: '/pages/home/home'
        })
      }
    })
  }
  // 工具函数
  // 生成一个包含大图的数组
  function generateNewArrByPaperList() {
    return paperList.value.map(p => {
      return {
        ...p,
        bigPicUrl: p.smallPicurl.replace('_small.webp', '.jpg')
      }
    })
  }
  // 将看过的图片和与它相邻的前后两张图片添加到数组中
  function browsedPaperwall() {
    browsedList.value.push(
      current.value === 0 ? paperList.value.length - 1 : current.value - 1,
      current.value,
      current.value === paperList.value.length - 1 ? 0 : current.value + 1)
    browsedList.value = [...(new Set(browsedList.value))];
  }
</script>

<style lang="scss" scoped>
  // 预览页面
  .container {
    position: relative;

    // 滑动试图
    .swiper-box {
      height: 100vh;

      .swiper-item {
        width: 100%;
        height: 100%;

        .img {
          width: 100%;
          height: 100%;
        }
      }
    }

    // 透明遮罩
    .mask-box {
      &>view:not(.back-box) {
        position: absolute;
        left: 0%;
        right: 0;
        margin: auto;
        width: fit-content;
      }

      .back-box {
        left: 10px;
        position: absolute;

        :deep() {
          .uni-icons {
            color: #fff !important;
            border-radius: 50%;
            border: 2px solid white;
          }
        }

      }


      .indicator-box {
        top: 10vh;
        width: fit-content;
        background-color: rgba(0, 0, 0, .3);
        backdrop-filter: blur(10rpx);
        border-radius: 20px;
        padding: 10rpx 20rpx;
        color: white;
      }

      .time-box {
        top: calc(10vh + 86rpx);
        font-size: 118rpx;
        color: #fff;
      }

      .date-box {
        color: $text-color-shallow;
        top: calc(10vh + 235rpx);
        font-size: 35rpx;
      }

      .footer-box {
        display: flex;
        justify-content: space-around;
        bottom: 15vh;
        background-color: rgba(255, 246, 239, 0.8);
        backdrop-filter: blur(10px);
        border-radius: 50px;
        padding: 5px 0;

        .item-box {
          padding: 0 8px;

          .text {
            font-size: 14px;
            margin-top: 5px;
          }
        }

      }
    }

    // 信息弹窗
    .detailpopup-box {
      background-color: #fff;
      border-radius: 10px 10px 0 0;
      padding-bottom: env(safe-area-inset-bottom);

      .scroll-y {
        max-height: 50vh;

        .row {
          display: flex;
          padding: 20rpx 0;

          .label {
            width: 153rpx;
            text-align: right;
            color: $text-color-second;
            font-size: 32rpx;
          }

          .value.tag-box {
            display: flex;
          }

          .value {
            flex: 1;
            width: 0;

            .tag {
              border: 1px solid $theme-color;
              border-radius: 30px;
              color: $theme-color;
              width: fit-content;
              padding: 5rpx 20rpx;
              font-size: 22rpx;
              margin-right: 8rpx;
            }
          }
        }

        .declaration {
          margin: 10px;
          background-color: #e7e7e7;
          border-radius: 10px;
          padding: 15px 9px;
          color: $text-color-second;
        }
      }
    }

    // 评分弹窗
    .rate-container {
      width: 526rpx;
      height: 328rpx;
      background-color: #fff;
      border-radius: 10px;
      text-align: center;

      .score {
        display: flex;
        justify-content: space-evenly;
      }

      .confirm-btn {
        margin-top: 47rpx;
        border: 1px solid black;
        background-color: white;
      }
    }
  }
</style>